package com.jcfk.eam.service.main;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jcfk.eam.domain.dto.base.EamRepairOrderDTO;
import com.jcfk.eam.domain.po.base.EamRepairOrder;
import com.jcfk.eam.domain.po.main.EamWorkOrderRecord;
import com.jcfk.eam.domain.query.main.EamWorkOrderRecordQuery;
import com.jcfk.eam.domain.dto.main.EamWorkOrderRecordDTO;
import com.jcfk.eam.dao.main.EamWorkOrderRecordDao;
import com.jcfk.common.business.service.BaseService;
import com.jcfk.common.web.domain.DataPage;
import com.jcfk.common.web.domain.RetResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jcfk.eam.enums.RepairOrderRecordOperateType;
import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;
import com.jcfk.common.core.utils.BeanUtils;
import cn.hutool.core.util.StrUtil;
import com.jcfk.common.security.utils.SecurityUtils;
import com.alibaba.druid.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.ArrayList;

import static com.jcfk.common.core.utils.BeanUtils.convertList;

import java.util.Date;
import java.util.stream.Collectors;

/**
 * 作业工单处理记录
 *
 * @author awei
 * @email 522891237@gqq.com
 * @date 2024-09-04
 */
@Service
public class EamWorkOrderRecordService extends BaseService<EamWorkOrderRecordDao, EamWorkOrderRecord> {


    @Resource
    private EamRepairOrderService eamRepairOrderService;
    /**
     * EamWorkOrderRecord分页查询
     *
     * @param page  分页设置
     * @param query 查询条件
     * @return 分页查询结果
     */
    public DataPage<EamWorkOrderRecordDTO> queryByPage(DataPage<EamWorkOrderRecordDTO> page, EamWorkOrderRecordQuery query) {
        // 分页查询
        page = this.baseMapper.queryByPage(page, query);
        return page;
    }


    /**
     * 判断EamWorkOrderRecord是已经存在
     *
     * @param dto
     * @return
     */
    public RetResult<String> isValid(EamWorkOrderRecordDTO dto) {
        QueryWrapper<EamWorkOrderRecord> queryWrapper = new QueryWrapper<>();

        return RetResult.ok();
    }

    /**
     * 插入作业工单处理记录
     *
     * @param dto 插入对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(EamWorkOrderRecordDTO dto) {

        // 保存
        EamWorkOrderRecord item = new EamWorkOrderRecord();
        BeanUtils.copyProperties(dto, item);
        this.setDefaultValue(item);

        super.save(item);
    }

    /**
     * 更新作业工单处理记录
     *
     * @param dto 更新对象
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(EamWorkOrderRecordDTO dto) {

        // 保存
        EamWorkOrderRecord item = new EamWorkOrderRecord();
        BeanUtils.copyProperties(dto, item);

        // 默认数据
        this.setDefaultValue(item);

        super.updateById(item);
    }


    /**
     * 设置添加默认值
     *
     * @param item 添加对象
     */
    public void setDefaultValue(EamWorkOrderRecord item) {
        if (StrUtil.isEmpty(item.getCreatedUserId())) {
            item.setCreatedUserId(SecurityUtils.getUserId());
            item.setCreateTime(new Date());
            item.setVersion(1L);
            item.setCreatedUserName(SecurityUtils.getUserName());
        }
        item.setLastUpdatedUserId(SecurityUtils.getUserId());
        item.setLastUpdateTime(new Date());

        item.setLastUpdatedUserName(SecurityUtils.getUserName());

    }

    /**
     * 根据主键获取作业工单处理记录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public EamWorkOrderRecordDTO get(String id) {
        // 查询数据
        EamWorkOrderRecord item = this.baseMapper.selectById(id);
        EamWorkOrderRecordDTO dto = new EamWorkOrderRecordDTO();
        try {
            BeanUtils.copyProperties(item, dto);
        } catch (RuntimeException e) {
            throw e;
        }

        return dto;
    }

    /**
     * 作业工单处理记录批量保存
     *
     * @param dtos
     * @return StandardCodeDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveBatch(List<EamWorkOrderRecordDTO> dtos, String id) {
        List<EamWorkOrderRecord> insertList = new ArrayList<>();
        List<EamWorkOrderRecord> updateList = new ArrayList<>();
        List<String> notDeleteIds = new ArrayList<>();


        for (EamWorkOrderRecordDTO dto : dtos) {
            EamWorkOrderRecord item = new EamWorkOrderRecord();
            BeanUtils.copyProperties(dto, item);
            this.setDefaultValue(item);

            if (!StringUtils.isEmpty(dto.getId())) {
                notDeleteIds.add(dto.getId());
                updateList.add(item);
            } else {
                insertList.add(item);
            }
        }

        // 删除
        QueryWrapper<EamWorkOrderRecord> queryWrapper = new QueryWrapper<>();
        if (notDeleteIds.size() > 0) queryWrapper.notIn("id", notDeleteIds);
        queryWrapper.lambda().eq(EamWorkOrderRecord::getOrderId, id);
        this.remove(queryWrapper);

        // 保存新增
        if (insertList.size() > 0) this.saveBatch(insertList);

        // 保存更新
        if (updateList.size() > 0) this.updateBigBatch(updateList);
    }


    /**
     * 根据条件获取单表信息列表
     *
     * @param query 查询条件
     * @return List<EamWorkOrderRecordDTO>
     */
    public List<EamWorkOrderRecordDTO> getList(EamWorkOrderRecordQuery query) {
        // 查询条件
        QueryWrapper<EamWorkOrderRecord> qw = new QueryWrapper<>();
        qw.lambda().eq(!StrUtil.isEmpty(query.getOrderId()), EamWorkOrderRecord::getOrderId, query.getOrderId());
        qw.lambda().ge(!StrUtil.isEmpty(query.getOperateTimeStart()), EamWorkOrderRecord::getOperateTime, query.getOperateTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getOperateTimeEnd()), EamWorkOrderRecord::getOperateTime, query.getOperateTimeEnd());
        qw.lambda().ge(!StrUtil.isEmpty(query.getResponseTimeStart()), EamWorkOrderRecord::getResponseTime, query.getResponseTimeStart());
        qw.lambda().le(!StrUtil.isEmpty(query.getResponseTimeEnd()), EamWorkOrderRecord::getResponseTime, query.getResponseTimeEnd());
        qw.lambda().eq(query.getIsResponse() != null, EamWorkOrderRecord::getIsResponse, query.getIsResponse());
        // 查询数据
        List<EamWorkOrderRecord> list = super.list(qw);

        return convertList(list, EamWorkOrderRecordDTO.class);
    }

    /**
     * 根据主键获取作业工单处理记录信息
     *
     * @param id 主键
     * @return StandardCodeDTO
     */
    public void deleteItem(String id) {
        this.removeById(id);
    }


    @Transactional
    public void saveRepairRecord(EamRepairOrder order, RepairOrderRecordOperateType type){
        saveRepairRecord(order, type, null);
    }

    @Transactional
    public void saveRepairRecord(EamRepairOrder order, RepairOrderRecordOperateType type, String extra){
        EamWorkOrderRecord record = new EamWorkOrderRecord();
        record.setOrderId(order.getId());
        record.setOperaterId(SecurityUtils.getUserId());
        record.setOperaterName(SecurityUtils.getUserName());
        record.setOperateTime(new Date());
        record.setOperateType(type.getDesc());
        record.setOperateResult(extra);
        this.setDefaultValue(record);
        super.save(record);
    }

    public List<EamWorkOrderRecordDTO> getByOrderId(String orderId) {
        EamRepairOrderDTO eamRepairOrderDTO = eamRepairOrderService.get(orderId);
        return this.list(Wrappers.<EamWorkOrderRecord>lambdaQuery()
                .eq(EamWorkOrderRecord::getOrderId, orderId)
                .orderByAsc(EamWorkOrderRecord::getOperateTime))
            .stream()
            .map(t -> {
                EamWorkOrderRecordDTO eamWorkOrderRecordDTO = new EamWorkOrderRecordDTO();
                BeanUtils.copyProperties(t, eamWorkOrderRecordDTO);
                eamWorkOrderRecordDTO.setRepairCode(eamRepairOrderDTO.getRepairCode());
                return eamWorkOrderRecordDTO;
            })
            .collect(Collectors.toList());
    }
}

